package com.cloudxingkong.dianyinke.NewTeacher.Ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.cloudxingkong.dianyinke.BuildConfig;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.LoginJsonUtils;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.MD5Utils;
import com.cloudxingkong.dianyinke.NewTeacher.config.Constans;
import com.cloudxingkong.dianyinke.R;
import com.cloudxingkong.dianyinke.Student.Ui.MainActivity;
import com.cloudxingkong.dianyinke.Uri.teacherUri.ThisUri;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.http.cookie.DbCookieStore;
import org.xutils.x;

import java.net.HttpCookie;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class Login extends AppCompatActivity {

	private EditText etPhoneNo;
	private EditText etPassword;
	private String getPassword;
	private String getPhoneNo;

	private ProgressDialog progressDialog;
	private SharedPreferences sharedPreferences;
	private Button btnLogin;

	@Override
	protected void onCreate (Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);
		setContentView (R.layout.activity_login_backup);
		etPhoneNo = (EditText) findViewById (R.id.login_et_phoneno);
		etPassword = (EditText) findViewById (R.id.login_et_pwd);
		btnLogin = (Button) findViewById (R.id.login_btn_login);

		sharedPreferences = getSharedPreferences ("data_dyk", 0);

	}

	boolean bool = true;

	public void onTest (View view) {
		if (BuildConfig.DEBUG) {

			if (bool) {
				etPhoneNo.setText ("18668247775");
				Toast.makeText (this, "老师", Toast.LENGTH_SHORT).show ();
			} else {
				etPhoneNo.setText ("18768115633");
				Toast.makeText (this, "学生", Toast.LENGTH_SHORT).show ();
			}
			bool = !bool;
			etPassword.setText ("123456");
		}
	}

	//欢迎界面
	private static Boolean isExit = false;
	private static Boolean hasTask = false;
	Timer tExit = new Timer ();
	TimerTask task = new TimerTask () {
		@Override

		public void run () {
			isExit = true;
			hasTask = true;
		}
	};

	@Override
	public boolean onKeyDown (int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (isExit == false) {
				isExit = true;
				Toast.makeText (Login.this, "再按一次退出程序", Toast.LENGTH_SHORT).show ();
				if (!hasTask) {
					tExit.schedule (task, 2000);
				}
			} else {
				finish ();
				System.exit (0);
			}
		}
		return false;
	}

	public void login (View view) {
		switch (view.getId ()) {
			case R.id.login_zhuce:   //注册
				Intent intent = new Intent (this, Zhuce.class);
				startActivityForResult (intent, Constans.LOGIN_TO_REQUEST);
				break;
			case R.id.login_btn_login: //登录
				if (TextUtils.isEmpty (etPhoneNo.getText ()) || TextUtils.isEmpty (etPassword.getText ())) {
					Toast.makeText (this, "请输入用户名或密码！", Toast.LENGTH_SHORT).show ();
				} else {
					loginRequest ();
				}
				break;
			case R.id.login_btn_wangji:  //忘记密码
				startActivityForResult (new Intent (this, UpdatePsd.class), Constans.LOGIN_TO_MODIFY_REP);
				break;
		}
	}

	private void loginRequest () {
		progressDialog = ProgressDialog.show (this, null, "正在登录....", true, false);

		getPassword = etPassword.getText ().toString ();
		getPhoneNo = etPhoneNo.getText ().toString ();
		String pwdMD5 = MD5Utils.getMD5 (getPassword);
		Log.e ("test", "登录 MD5加密 " + MD5Utils.getMD5 (getPassword));


		RequestParams params = new RequestParams (ThisUri.SERVER_YUMING + ThisUri.USER_LOGIN);
		params.addBodyParameter ("uname", getPhoneNo);
		params.addBodyParameter ("upwd", pwdMD5);

		x.http ().post (params, new Callback.CommonCallback<String> () {
			@Override
			public void onSuccess (String result) {
				HashMap<String, Object> fromLogin = LoginJsonUtils.getJsonFromLogin (result);
				Log.e ("test", fromLogin.get ("success") + "---" + result);
				boolean b = (boolean) (fromLogin.get ("success"));
				if (b == true) {

					DbCookieStore cookieStore = DbCookieStore.INSTANCE;
					List<HttpCookie> cookies = cookieStore.getCookies ();
					for (int i = 0; i < cookies.size (); i++) {
						Log.e ("test", "欢迎页使用xUtils尝试获取cookie " + i + " : " + cookies.get (i));
						SharedPreferences.Editor edit = sharedPreferences.edit ();
						edit.putString ("sessionID", cookies.get (i) + "");
						edit.commit ();
					}

					if (fromLogin.get ("memtype").equals ("teacher")) {

						Toast.makeText (Login.this, "老师端登录成功！", Toast.LENGTH_SHORT).show ();
						Log.e ("test", "密码正确 老师登录成功 " + result);

						SharedPreferences.Editor editor = sharedPreferences.edit ();
						editor.putString ("userPhone", getPhoneNo);
						editor.putString ("userPwd", getPassword);
						editor.putString ("memtype", fromLogin.get ("memtype").toString ());
						editor.commit ();

						progressDialog.dismiss ();
						startActivity (new Intent (Login.this, TeacherMainActivity.class));
						finish ();
					} else if (fromLogin.get ("memtype").equals ("student")) {

						Toast.makeText (Login.this, "学生端登录成功！", Toast.LENGTH_SHORT).show ();
						Log.e ("test", "密码正确 学生登录成功 " + result);

						SharedPreferences.Editor editor = sharedPreferences.edit ();
						editor.putString ("userPhone", getPhoneNo);
						editor.putString ("userPwd", getPassword);
						editor.putString ("memtype", fromLogin.get ("memtype").toString ());
						editor.commit ();

						progressDialog.dismiss ();
						startActivity (new Intent (Login.this, MainActivity.class));
						finish ();
					}
				} else {
					Log.e ("test", "密码错误 登录失败 " + result);
					progressDialog.dismiss ();
					Toast.makeText (Login.this, "登录失败，请检查用户名和密码", Toast.LENGTH_SHORT).show ();
				}


			}

			@Override
			public void onError (Throwable ex, boolean isOnCallback) {
				progressDialog.dismiss ();
				Toast.makeText (Login.this, "登陆失败，请稍后重试！", Toast.LENGTH_SHORT).show ();
			}

			@Override
			public void onCancelled (CancelledException cex) {

			}

			@Override
			public void onFinished () {

			}
		});
	}

	@Override
	protected void onActivityResult (int requestCode, int resultCode, Intent data) {
		if (requestCode == Constans.LOGIN_TO_REQUEST) {
			switch (resultCode) {
				case Constans.LOGIN_TO_REG_REP:    //注册页面返回
					String userPhone = sharedPreferences.getString ("userPhone", "");
					String userPwd = sharedPreferences.getString ("userPwd", "");
					etPhoneNo.setText (userPhone);
					etPassword.setText (userPwd);
					login (btnLogin);
					break;
			}
		}
		super.onActivityResult (requestCode, resultCode, data);
	}
}
